import 'package:flutter/material.dart';

/// 扩展Widget，使其具备padding，click等功能
extension WidgetExt on Widget {
  Widget size({double width, double height}) =>
      SizedBox(width: width, height: height, child: this);

  /// padding
  Widget padding(EdgeInsetsGeometry edgeInsetsGeometry) => Padding(
        padding: edgeInsetsGeometry,
        child: this,
      );

  /// 点击事件
  Widget click(GestureTapCallback onTap,
          {HitTestBehavior behavior = HitTestBehavior.opaque}) =>
      GestureDetector(
        onTap: onTap,
        behavior: behavior,
        child: this,
      );

  /// 点击 and 长按
  Widget gesture(
      {GestureTapCallback onTap, GestureLongPressCallback onLongPress}) {
    return GestureDetector(
      onTap: onTap,
      onLongPress: onLongPress,
      child: this,
    );
  }

  /// 是否可见
  Widget visible(bool visible) {
    return Offstage(
      offstage: !visible,
      child: this,
    );
  }

  Widget expanded({int flex = 1}) => Expanded(
        child: this,
        flex: flex,
      );

  Widget align(Alignment alignment) {
    return Align(
      alignment: alignment,
      child: this,
    );
  }

  Widget center() => Center(child: this);
}

extension ListExt<T> on List<T> {
  /// 对于List.isNullOrEmpty无需判空
  bool get isNullOrEmpty {
    if (this == null) return true;

    return this.isEmpty;
  }

  /// 安全的索引，避免下表越界
  T getOrNull(int index) {
    if (this == null ||  index >= this.length || index < 0) {
      return null;
    }

    return this[index];
  }

  void forEachIndexed(void action(int index, T element)) {
    if (this.isNullOrEmpty) return;

    var index = 0;
    for (T element in this) action(index++, element);
  }
}

/// 对于String.isNullOrEmpty调用无需判空
extension StringExt on String {
  bool get isNullOrEmpty {
    if (this == null) return true;

    return this.isEmpty;
  }
}
